$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'goodsConfigChangePrice/goodsconfigchangeprice/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true },
			{ label: 'spu', name: 'spu', index: 'spu', width: 80 }, 			
			{ label: 'sku', name: 'sku', index: 'sku', width: 80 },
            { label: '商品名称', name: ' goodsName ', index: 'goods_name', width: 80 },
			{ label: '描述', name: 'describes', index: 'describes', width: 80 }, 			
			{ label: '新价格', name: 'changePrice', index: 'change_price', width: 80 }, 			
			{ label: '扩展价变价（大纸平板）', name: 'changeExpandPrice', index: 'change_expand_price', width: 80 }, 			
			{ label: '变价类型', name: 'changeType', index: 'change_type', width: 80 ,
                formatter:function(value){
                    if(value == 'normal'){
                        return '普通';
                    }else if(value == 'seckill'){
                        return '秒杀';
                    }else if(value == 'group'){
                        return '团购'
                    }
                }
            },
			{ label: '变价单价', name: 'changeSinglePrice', index: 'change_single_price', width: 80 }, 			
			{ label: '变价参数', name: 'changeParam', index: 'change_param', width: 80 }, 			
			{ label: '限购单人次数', name: 'limitTimes', index: 'limit_times', width: 80 }, 			
			{ label: '限购总次数', name: 'limitTotal', index: 'limit_total', width: 80 }, 			
			{ label: '操作人员', name: 'operationUser', index: 'operation_user', width: 80 }, 			
			{ label: '开始时间', name: 'startTime', index: 'start_time', width: 80 }, 			
			{ label: '结束时间', name: 'endTime', index: 'end_time', width: 80 }, 			
			// { label: '创建时间', name: 'createTime', index: 'create_time', width: 80 },
			// { label: '更新时间', name: 'updateTime', index: 'update_time', width: 80 },
			// { label: '失效:0-不失效 1-失效', name: 'disabled', index: 'disabled', width: 80 }
        ],
		viewrecords: true,
        height: 650,
        rowNum: 20,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    // 线获取添加模板基本信息
    $.get(baseURL + "goodsCategory/goodscategory/getCategoryTree", function(r){
        vm.categoryTree = r.addInfo.categoryTree;
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		goodsConfigChangePrice: {

		},
        goodsCategoryDialogVisible:false,
        categoryId: null, //分类id
        categoryTree:[], //商品分类树
        catId:null,
        spuTableData:null,
        skuTableData:null,
        spuQuery:{
            goodsId:null,
            name:null,
            catId:null
        },
        productData:[],
        q:{
            productId:'',
            goodsName:'',
            goodsType:'',
            changeType:'',
            status:''
        }
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.goodsConfigChangePrice = {};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
        reset:function(){
            vm.q.productId = '';
            vm.q.goodsName = '';
            vm.q.goodsType = '';
            vm.q.changeType = '';
            vm.q.status = '';
        },
		saveOrUpdate: function (event) {
			var url = vm.goodsConfigChangePrice.id == null ? "goodsConfigChangePrice/goodsconfigchangeprice/save" : "goodsConfigChangePrice/goodsconfigchangeprice/update";
			//遍历productData    goodsConfigChangePrice
            //goodsConfigChangePrice
            var goodsConfigChangePriceList = [];
            for(var i = 0;i<vm.productData.length;i++){
                var goodsConfigChangePrice = JSON.parse(JSON.stringify(vm.goodsConfigChangePrice));//深克隆
                goodsConfigChangePrice.spu = vm.productData[i].spu;
                goodsConfigChangePrice.sku = vm.productData[i].sku;
                goodsConfigChangePrice.changePrice = vm.productData[i].changePrice;
                ;
                if(isBlank(goodsConfigChangePrice.changePrice)){
                    alert("修改后的价格不能为空!")
                    return
                }
                goodsConfigChangePrice.goodsName = vm.productData[i].goodsName;
                goodsConfigChangePriceList.push(goodsConfigChangePrice);
            }
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(goodsConfigChangePriceList),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "goodsConfigChangePrice/goodsconfigchangeprice/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "goodsConfigChangePrice/goodsconfigchangeprice/info/"+id, function(r){
                vm.goodsConfigChangePrice = r.goodsConfigChangePrice;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
                postData:{
                    productId:vm.q.productId,
                    goodsName:vm.q.goodsName,
                    goodsType:vm.q.goodsType,
                    changeType:vm.q.changeType,
                    status:vm.q.status
                }
            }).trigger("reloadGrid");
		},
        choiceCategory:function(){
            vm.goodsCategoryDialogVisible = true;
        },
        //树结构选中变化时
        categoryChange:function(value){
            //取到末级的分类id
            vm.catId = value[value.length-1];
            //根据分类请求后台判断分类属性
            var goodsCategory = {};
            $.get(baseURL+"goodsCategory/goodscategory/info/"+vm.catId,function(r){
                goodsCategory = r.goodsCategory;
                if(goodsCategory.goodsType != 'standard'){
                    // this.$message.error('该功能只支持标品,请选择标品分类!');
                    vm.$message({
                        showClose: true,
                        message: '该功能只支持标品,请选择标品分类!',
                        type: 'warning'
                    });
                }else{
                    //调用接下来的步骤
                    vm.goodsCategoryDialogVisible = false;
                    //加载spu数据
                    vm.loadSpuData();
                }
            });

        },
        loadSpuData:function(){
            //ajax请求获得该分类下的spu列表
            // $.get(baseURL + "goods/goods/goodsList/"+catId, function(r){
            //    vm.spuTableData = r.spuTableData;
            // });
            var query = {};
            if(!isBlank(vm.spuQuery.goodsId)){
                query.goods_id= vm.spuQuery.goodsId;
            }
            if(!isBlank(vm.spuQuery.name)){
                query.name= vm.spuQuery.name;
            }
            query.disabled = 0;
            query.category_id = vm.catId;
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goods/goodsList",
                contentType: "application/json",
                data: JSON.stringify(query),
                success: function(r){
                    if(r.code == 0){
                        vm.spuTableData = r.spuTableData;
                    }else{
                        alert(r.msg);
                    }
                }
            });
            vm.skuTableData = null
        },
        choiceSpu:function(row){
            var goodsId = row.goodsId
            if(isBlank(goodsId)){
                vm.$message({
                    showClose: true,
                    message: '异常信息:spu不存在,请联系管理员!',
                    type: 'warning'
                });
                return;
            }
            var skuQuery = {}
            skuQuery.disabled = 0;
            skuQuery.goods_id = goodsId;
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goodsproduct/selectProductByGoodsId",
                contentType: "application/json",
                data: JSON.stringify(skuQuery),
                success: function(r){
                    if(r.code == 0){

                        vm.skuTableData = r.skuTableData;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        choiceSku:function(row){
            //获得skuId和规格属性中文
            var product = {};
            //goodsId productId totalPrice changePrice
            product.spu = row.goodsId;
            product.sku = row.productId;
            product.totalPrice = row.totalPrice;
            product.goodsName = row.goodsName;
            product.changePrice = null;
            if(row.addOrDel == false){
                row.addOrDel = true;
                vm.productData.push(product);
			}else{
                row.addOrDel = false;
                // vm.productData.splice(vm.productData.indexOf(product),1)
                for(var i = 0 ;i<vm.productData.length;i++){
                    if(vm.productData[i].productId == product.sku){
                        vm.productData.splice(i,1);
                        return;
                    }
                }
			}
        },
        setScale:function(){
            this.$confirm('稍后会按照利率设置所有sku的新价格, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                for(var i = 0;i<vm.productData.length;i++){
                    vm.productData[i].changePrice = (vm.productData[i].totalPrice * vm.goodsConfigChangePrice.scale).toFixed(2);
                }
                this.$message({
                type: 'success',
                message: '设置成功!'
                });
            }).catch(() => {
                    this.$message({
                    type: 'info',
                    message: '已取消设置'
                });
            });
        },
        choiceTime:function(){
            for(var i = 0;i<vm.productData.length;i++){
                vm.productData[i].changePrice = (vm.productData[i].totalPrice * vm.goodsConfigChangePrice.scale).toFixed(2);
            }
        }
	}
});